package common;

import org.eclipse.swt.graphics.ImageData;


public class ImageMap {
	private ImageData imgData;

	public ImageMap(ImageData imgData){
		this.imgData = imgData;
	}

	private double parametrizeX(double x){
		return (x) * (imgData.width-1); 
	}
	private double parametrizeY(double y){
		return (y) * (imgData.height-1);
	}
	private double getValue(int x, int y){
		if (imgData == null)
			return 0;
		x = x % imgData.width;
		y = y % imgData.height;
		return (imgData.getPixel(x, y) & 0xff) / (double)0xff;
	}

	public double sampleBilinear(Parameterization2D pmz) {
		double x = parametrizeX(pmz.x);
		double y = parametrizeY(pmz.y);
		int x1 = (int)Math.floor(x);
		int y1 = (int)Math.floor(y);
		int x2 = (int)Math.floor(x)+1;
		int y2 = (int)Math.floor(y)+1;
		
		return getValue(x1, y1) * (x2-x) * (y2-y)
		+ getValue(x2, y2) * (x-x1) * (y-y1)
		+ getValue(x2, y1) * (x-x1) * (y2-y)
		+ getValue(x1, y2) * (x2-x) * (y-y1);
	}
	

}
